package com.rh.manage.listener;

import com.rh.manage.annotation.ComponentBean;
import com.rh.manage.constants.FrameCategoryEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * 从factory上将控件设置到view中
 */
@ComponentBean(FrameCategoryEnum.PRO_MANAGE)
public class FactoryAutowiredListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private ApplicationContext context;
    private List<Runnable> runnableList;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (!context.equals(event.getApplicationContext())) {
            return;
        }
        if (CollectionUtils.isEmpty(runnableList)) {
            return;
        }
        runnableList.forEach(Runnable::run);
        runnableList.clear();
    }

    public void add(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        if (CollectionUtils.isEmpty(runnableList)) {
            runnableList = new ArrayList<>(20);
        }
        runnableList.add(runnable);
    }

    private void clear() {
        runnableList = null;
    }
}
